<?php
class MemberAction extends CommonAction {
	private $igoneAction = array('login', 'register', 'forget', 'forgetresult', 'oauthback', 'oauth');
	public function __construct(){
		parent::__construct();
		
		$this->modelObject = D('Member');
		$this->modelSnsObject = D('MemberSns');
		
		//判断用户登录信息
		if(!($this->memberInfo = $this->getMemberInfo()) && !in_array(ACTION_NAME, $this->igoneAction)){
			redirect(U('/login'));
		}else if($this->memberInfo && in_array(ACTION_NAME, $this->igoneAction)){
			if(IS_POST || IS_AJAX){
				$this->unsetMemberInfo(false);
				$this->ACTION_NAME.'()';	
			}else{
				redirect(U('index'));
			}
		}
    }
	
    public function index(){
		$this->setSeo(array('title'=>'会员中心'));
		
		$this->assign('info', $this->memberInfo);
		$this->display();	
    }
	
	public function register(){
		$this->setSeo(array('title'=>'会员注册'));
		
		if(IS_POST || IS_AJAX){
			$username    = I('username', '', 'trim');
			$password    = I('password', '', 'trim');
			$relpassword = I('relpassword', '', 'trim');
			//如果用户名跟前缀冲突，那么提示用户名是存在的
			if(C('OAUTH_PREFIX') != '' && strtolower(substr($username,0,strlen(C('OAUTH_PREFIX')))) == strtolower(C('OAUTH_PREFIX'))){
				$this->error('您输入的用户名已经存在!');	
			}
			
			if(!isEmail($username)){
				$this->error('用户名请使用邮箱账号!');	
			}
			
			if((empty($password) || empty($relpassword)) || ($password != $relpassword)){
				$this->error('两次密码输入错误!');	
			}
			
			if($this->modelObject->getByUsername($username)){
				$this->error('您输入的用户名已经存在!');		
			}
			
			$_POST['pwd_salt'] = randString();
			$_POST['add_time'] = $_POST['last_login_time'] = NOW_TIME;
			$_POST['password'] = setPassword($password, $_POST['pwd_salt']);
			if($this->modelObject->create()){
				if($insertId = $this->modelObject->add()){
					//保存会员信息
					$this->setMemberInfo($insertId);
					redirect(U('index'));
				}else{
					$this->error('会员注册失败!');
				}
			}else{
				$this->error('会员注册失败!');
			}
		}else{
			$this->display();
		}
	}
	
	public function login(){
		$this->setSeo(array('title'=>'会员登录'));
		
		if(IS_POST || IS_AJAX){
			$username    = I('username', '', 'trim');
			$password    = I('password', '', 'trim');
			if(!isEmail($username)){
				$this->error('用户名和密码输入错误!');	
			}
			
			if((empty($password) || empty($username))){
				$this->error('用户名和密码输入错误!');	
			}
			
			if($memberInfo = $this->modelObject->getByUsername($username)){
				if($memberInfo['password'] == setPassword($password, $memberInfo['pwd_salt'])){
					//保存会员信息
					$this->setMemberInfo(0, $memberInfo);
					redirect(U('index'));
				}else{
					$this->error('用户名和密码输入错误!');		
				}
			}else{
				$this->error('用户名和密码输入错误!');		
			}
		}else{
			$this->display();
		}	
	}
	
	public function logout(){
		$this->unsetMemberInfo();
	}
	
	public function changepwd(){
		$this->setSeo(array('title'=>'修改密码'));
		
		if(IS_POST || IS_AJAX){
			$oldpassword = I('oldpassword', '', 'trim');
			$password = I('password', '', 'trim');
			$relpassword = I('relpassword', '', 'trim');
			
			if(setPassword($oldpassword, $this->memberInfo['pwd_salt']) != $this->memberInfo['password']){
				$this->error('原始密码不正确!');	
			}
			
			if(empty($password) || empty($relpassword) || $password != $relpassword){
				$this->error('两次输入的密码不一致!');		
			}
			
			if($oldpassword == $relpassword){
				$this->error('新密码不能和原始密码一致!');		
			}
			
			if($this->modelObject->changePassword($this->memberInfo['id'], setPassword($password,$this->memberInfo['pwd_salt']))){
				$this->unsetMemberInfo(false);
				$this->success('密码修改成功,请重新登录!',U('/login'));	
			}else{
				$this->error('密码修改失败!');		
			}
		}else{
			$this->display();
		}	
	}
	
	public function forget(){
		$this->setSeo(array('title'=>'找回密码'));
		
		if(IS_POST || IS_AJAX){
			$username    = I('username', '', 'trim');
			
			//如果用户名跟前缀冲突，那么提示用户名是存在的
			if((C('OAUTH_PREFIX') != '' && strtolower(substr($username,0,strlen(C('OAUTH_PREFIX')))) == strtolower(C('OAUTH_PREFIX'))) || !isEmail($username)){
				$this->error('您输入的用户名不正确!');	
			}else{
				//查找用户是否存在
				if($memberInfo = $this->modelObject->getInfo(array('username'=>$username, 'status'=>1))){
					//更新该用户的forgetkey和forgettime
					$data = array();
					$data['id']         = $memberInfo['id'];
					$data['forgetkey']  = md5($memberInfo['id'].NOW_TIME);
					$data['forgettime'] = NOW_TIME;
					$this->modelObject->save($data);
					/*发送邮件开始*/
					$content = '<strong>尊敬的'.$this->webConfig['web_name'].'会员：</strong><br>';
					$content .= '请您点击下面链接来修复帐号登录密码:<br>'.U('/forgetresult').'?token='.$data['forgetkey'];
					$content .= '<br>为了确保您的帐号安全，该链接仅60分钟内访问有效。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$this->webConfig['web_name'];
					sendMail($username, $this->webConfig['web_name'].'的密码找回信息', $content);
					$this->success('找回密码认证已经发到您的邮箱，请根据邮箱的内容做进一步的操作!',U('/login'));
					/*发送邮件结束*/
				}else{
					$this->success('找回密码认证已经发到您的邮箱，请根据邮箱的内容做进一步的操作!');	
				}
			}
		}else{
			$this->display();
		}	
	}
	
	public function forgetresult(){
		$this->setSeo(array('title'=>'找回密码'));
		if(IS_POST || IS_AJAX){
			if($memberInfo = session('forgetMemberInfo')){
				session('forgetMemberInfo', NULL);
				
				$password = I('password', '', 'trim');
				$relpassword = I('relpassword', '', 'trim');
				
				if(empty($password) || empty($relpassword) || $password != $relpassword){
					$this->error('两次输入的密码不一致!');		
				}
				
				if($this->modelObject->changePassword($memberInfo['id'], setPassword($password, $memberInfo['pwd_salt']))){
					$this->unsetMemberInfo(false);
					
					$data = array();
					$data['forgetkey']  = '';
					$data['forgettime'] = 0;
					$data['id']         = $memberInfo['id'];
					$this->modelObject->save($data);
					
					$this->success('密码找回成功,请登录!',U('/login'));	
				}else{
					$this->error('密码找回失败,请重试!', U('/forget'));	
				}
			}else{
				$this->error('该链接已经失效，请重新提交找回密码操作! 0x00002', U('/forget'));	
			}
		}else{
			$resultCode = I('token', '');
			if(!empty($resultCode)){
				if($memberInfo = $this->modelObject->getInfo(array('forgetkey'=>$resultCode))){
					if(NOW_TIME - $memberInfo['forgettime'] > 3600){//链接1小时内有效
						$this->error('该链接已经失效，请重新提交找回密码操作! 0x00001', U('/forget'));	
					}else{
						session('forgetMemberInfo', $memberInfo);
						$this->display();
					}
				}else{
					$this->error('该链接已经失效，请重新提交找回密码操作! 0x00003', U('/forget'));	
				}
			}else{
				$this->error('参数有误!', U('/forget'));		
			}
		}
	}
	
	public function oauth(){
		$type = I('type', '', 'strtolower'); 
		if(in_array($type, array('qq', 'weixin'))){
			//加载ThinkOauth类并实例化一个对象
			Vendor('LoginSDK.ThinkOauth', '', '.class.php');
			$sns  = ThinkOauth::getInstance($type);
			//跳转到授权页面
			redirect($sns->getRequestCodeURL());
		}else{
			$this->go404();	
		}
	}
	
	//sns授权回调地址
	public function oauthback($type = NULL, $code = NULL){
		(empty($type) || empty($code)) && $this->error('返回参数有误!');
		
		//加载ThinkOauth类并实例化一个对象
		Vendor('LoginSDK.ThinkOauth', '', '.class.php');
		$sns  = ThinkOauth::getInstance($type);

		//腾讯微博需传递的额外参数
		$extend = NULL;
		if($type == 'tencent'){
			$extend = array('openid' => I('openid'), 'openkey' => I('openkey'));
		}
		
		/*
			appid	是	应用唯一标识，在微信开放平台提交应用审核通过后获得
			secret	是	应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
		*/

		//请妥善保管这里获取到的Token信息，方便以后API调用
		//调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
		//如： $qq = ThinkOauth::getInstance('qq', $token);
		$token = $sns->getAccessToken($code , $extend);
		
		//获取当前登录用户信息
		if(is_array($token)){
			//如果是绑定域名操作
			if($this->memberInfo['id'] > 0 && session('bind_sns')){
				//判断是否绑定过
				if($memberSnsInfo = $this->modelSnsObject->getInfo(array('sns_key'=>$token['openid'], 'sns_type'=>$type))){
					//更新下token资料
					$this->error('你之前已经绑定过了!', U('/member/bindSns'));
					exit;
				}else{//绑定账号
					$data = array();
					$data['member_id'] = $this->memberInfo['id'];
					$data['sns_key']   = $token['openid']; //SNS登录唯一标识键
					$data['sns_access']= $token['access_token']; //SNS登录唯一标识键
					$data['sns_type']  = $type;
					$data['add_time']  = NOW_TIME;
					
					if($this->modelSnsObject->add($data)){
						$this->success('绑定成功', U('/member/bindSns'));
					}else{
						$this->error('绑定失败', U('/member/bindSns'));		
					}
				}
				session('bind_sns', NULL); //清除标识
			}else{
				//如果已经绑定过。直接登录
				if($memberSnsInfo = $this->modelSnsObject->getInfo(array('sns_key'=>$token['openid'], 'sns_type'=>$type))){//绑定账号登录
					//更新下token资料
					$this->setMemberInfo($memberSnsInfo['member_id']);
				
					redirect(U('/member'));
				}else{ //注册
					$oauthUserInfo = A('Type', 'Event')->$type($token);
					
					$_POST['username'] = $token['openid'];
					$_POST['password'] = $token['openid'];
					$_POST['pic']      = $oauthUserInfo['head']; 
					$_POST['pwd_salt'] = randString();
					$_POST['add_time'] = NOW_TIME;
					$_POST['login_count']     = 1;
					$_POST['last_login_time'] = NOW_TIME;
					
					if($this->modelObject->create()){
						if($insertId = $this->modelObject->add()){
							//更新资料到绑定数据中
							$data = array();
							$data['member_id'] = $insertId;
							$data['sns_key']   = $token['openid']; //SNS登录唯一标识键
							$data['sns_access']= $token['access_token']; //SNS登录唯一标识键
							$data['sns_type']  = $type;
							$data['add_time']  = NOW_TIME;
							
							if($this->modelSnsObject->add($data)){
								//更改用户的用户名
								$data = array();
								$data['username'] = C('OAUTH_PREFIX').$insertId;
								$data['id']       = $insertId;
								$this->modelObject->save($data);
								
								//获得用户资料
								$this->setMemberInfo($insertId);
								redirect('/member');	
							}else{
								//如果注册失败。那么把注册信息也删了。
								$this->modelObject->delete($insertId);
								
								$this->error('联合登录信息保存失败', U('/login'));		
							}
						}else{
							$this->error('联合登录成功,但是注册失败!', U('/login'));		
						}
					}else{
						$this->error($member->getError());				
					}
					/*
					腾讯不允许强制用户再次注册
					您的网站审核未通过，原因是“禁止开发商强制用户重新注册或绑定其他帐号”，请确认申请符合审核标准后，再提交审核
					$memberInfo = A('Type', 'Event')->$type($token);
					session('sns_member_token', $token);
					session('sns_memberInfo', $memberInfo);
					session('sns_membe_type', $type);
					redirect(U('/snsregister'));*/
				}
			}
		}else{
			$this->error('联合登录获取不到返回信息,请刷新页面重试!', U('/login'));
		}
	}
	
	/*
	@param $relogin bool 是否重新登录
	*/
	private function getMemberInfo(){
		return session('memberInfo');
	}
	
	private function setMemberInfo($memberId, $memberInfo = NULL){
		if(!is_array($memberInfo)){
			$memberInfo = $this->modelObject->getInfo($memberId);
		}
			
		//更新会员信息
		$this->modelObject->updateLoginTime($memberInfo);
		
		session('memberInfo', $memberInfo);	
	}
	
	private function unsetMemberInfo($redirect = true){
		session('memberInfo', NULL);
		if($redirect){
			redirect(U('/login'));
		}
	}
	
	
	public function fav(){
		$modelObject = D('GoodBadView');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		$map['good'] = 1;
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage, 20, 'add_time DESC');
		foreach($list as $key=>$val){
			$list[$key]['url'] = setViewUrl('site', $val);	
		}
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage, 20);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'fav');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'我的收藏'));
		$this->display();
    }
	
	public function webapply(){
		$modelObject = D('Webapply');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		$map['is_recycle'] = 2;
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage);
		foreach($list as $key=>$val){
			$list[$key]['url'] = setViewUrl('site', $val);	
		}
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'webapply');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'审核列表'));
		$this->display();
    }
	
	public function websites(){
		$modelObject = D('Websites');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage);
		foreach($list as $key=>$val){
			$list[$key]['url'] = setViewUrl('site', $val);	
		}
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'websites');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'我的网站'));
		$this->display();
    }
	
	public function webapplydel(){
		$id = I('id', 0, 'intval');
		if($id && $this->memberInfo['id'] > 0){
			if(D('Webapply')->deleteInfo(array('id'=>$id, 'status'=>array('lt', 3), 'member_id'=>$this->memberInfo['id']))){
				$this->ajaxReturn(1, '删除成功', 1);
			}else{
				$this->ajaxReturn(0, '删除失败', 0);
			}
		}else{
			$this->ajaxReturn(0, '参数错误', 0);
		}
	}
	
	public function payment(){
		if(IS_POST){
			//1. 生成订单
			//`id`, `member_id`, `add_time`, `pay_time`, `recharge_no`, `amount`, `status`
			$rechargeObject = M('Recharge');
			$data = array();
			$data['member_id'] = $this->memberInfo['id'];
			$data['add_time']  = NOW_TIME;
			$data['recharge_no']  = date('YmdHis').randString(6,1);
			$data['amount']    = I('price', 0, 'intval');
			
			if($rechargeObject->add($data)){
				$_POST['recharge_no'] = $data['recharge_no'];
				$_POST['subject']  = $this->webConfig['web_name'].'积分充值';
				$_POST['amount']   = $data['amount'];
				//2.  调用支付接口
				Vendor('Payment.alipay.alipayapi');
			}
		}else{
			$this->setSeo(array('title'=>'在线充值'));
			$this->display();
		}
	}
	public function recharge(){
		$modelObject = D('Recharge');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage);
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'recharge');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'充值明细'));
		$this->display();
    }
	public function consumption(){
		$modelObject = D('Consumption');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage);
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'consumption');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'消费明细'));
		$this->display();
    }
	
	public function payquick(){
		$id = I('id', 0, 'intval');
		if($id && IS_AJAX){
			$thisMemberInfo = $this->modelObject->getInfo(array('id'=>$this->memberInfo['id']));
			if($thisMemberInfo['amount'] >= $this->webConfig['post_website_score']){
				$webapplyObject = M('Webapply');
				if($webapplyObject->where(array('id'=>$id,'member_id'=>$this->memberInfo['id']))->setField('status', 3)){
					$webapplyInfo = $webapplyObject->getInfo(array('id'=>$id));
					amountLog('submit_websites', array('domain'=>$webapplyInfo['domain']));
					$this->ajaxReturn(1, '我们已经收到您的快审请求,24小时之内即可审核您的网站!', 1);
				}else{
					$this->ajaxReturn(0, '提交快审失败', 0);
				}
			}else{
				$this->ajaxReturn(0, '您的余额不足，快审需要【'.$this->webConfig['post_website_score'].' 元】，请先充值!', 0);
			}
		}else{
			$this->ajaxReturn(0, '参数错误', 0);
		}
	}
	
	public function comment(){
		$modelObject = D('CommentWebsitesView');
		$thisPage = I('p', 1);
		
		$map['member_id'] = $this->memberInfo['id'];
		
		//获得列表
		$list = $modelObject->getPageList($map, $thisPage);
		foreach($list as $key=>$val){
			$list[$key]['web_url'] = setViewUrl('site', array('id'=>$val['target_id']));	
		}
		
		//分页
		$page = $modelObject->buildPage($map, $thisPage);
		$this->assign('page',$page);
		
		$this->assign('pageUrl', 'comment');
		$this->assign('list', $list);
		$this->setSeo(array('title'=>'我的评论'));
		$this->display();
    }
	
	public function commentdel(){
		$id = I('id', 0, 'intval');
		if($id && $this->memberInfo['id'] > 0){
			if(M('Comment')->deleteInfo(array('id'=>$id,'member_id'=>$this->memberInfo['id']))){
				$this->ajaxReturn(1, '删除成功', 1);
			}else{
				$this->ajaxReturn(0, '删除失败', 0);
			}
		}else{
			$this->ajaxReturn(0, '参数错误', 0);
		}
	}
}//end class